from .serializers import *
from apps.system.lessee.dao import LesseeDao
from apps.pay.order.dao import OrderDao
# from apps.pay.walletRecord.dao import WalletRecordDao
from apps.pay.financeForLessee.dao import FinanceForLesseeDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.pay.recordIncomesLocked.dao import RecordIncomesLockedDao
from apps.user.dao import UserDao

from django.db.models import Sum
from decimal import Decimal
import datetime
from django.db.models import Q

def financeFun(dateCycle, date):
    lessees = LesseeDao().findAll()
    for lessee in lessees:
        data = {}
        data['lessee'] = lessee.id
        data['dateCycle'] = dateCycle
        _itemOrder = OrderDao().findAll().filter(lessee=lessee).exclude(orderStatus='WAIT_PAY').exclude(orderStatus='CANCEL')
        _recordIncomes = RecordIncomesDao().findAll().filter(lessee=lessee)
        _recordIncomesLocked = RecordIncomesLockedDao().findAll().filter(lessee=lessee)
        _users = UserDao().findAll().filter(lessee=lessee, role='custom')

        # 微信支付总金额
        realPayALl = _itemOrder.filter(payway='wxpay').aggregate(sums=Sum('realPay'))
        data['realPayForWxPayAll'] = Decimal(realPayALl['sums']) if realPayALl['sums'] else 0
        # 积分支付总金额
        realPayForIncomesAll = _itemOrder.filter(payway='incomes').aggregate(sums=Sum('realPay'))
        data['realPayForIncomesAll'] = Decimal(realPayForIncomesAll['sums']) if realPayForIncomesAll['sums'] else 0
        # 订单支付总金额
        realPayALl = _itemOrder.aggregate(sums=Sum('realPay'))
        data['realPayALl'] = Decimal(realPayALl['sums']) if realPayALl['sums'] else 0
        # 总提现金额
        outMoneyAll = _recordIncomes.filter((Q(orderStatus='WAIT_SEND') | Q(orderStatus='FINISH')), scene='outMoney', ).aggregate(sums=Sum('money'))
        data['outMoneyAll'] = Decimal(outMoneyAll['sums']) if outMoneyAll['sums'] else 0
        # 总提现手续费
        outMoneyServiceChargeAll = _recordIncomes.filter((Q(orderStatus='WAIT_SEND') | Q(orderStatus='FINISH')), scene='outMoney', ).aggregate(sums=Sum('serviceCharge'))
        data['outMoneyServiceChargeAll'] = Decimal(outMoneyServiceChargeAll['sums']) if outMoneyServiceChargeAll['sums'] else 0
        # 结余可提现资产
        balanceIncomes = _users.aggregate(sums=Sum('incomes'))
        data['balanceIncomes'] = Decimal(balanceIncomes['sums']) if balanceIncomes['sums'] else 0
        # 结余锁仓本金
        balanceLockedCapital = _recordIncomesLocked.filter((Q(orderStatus='LOCKED') | Q(orderStatus='UNLOCKED')),scene='goldCustom', ).aggregate(sums=Sum('money'))
        data['balanceLockedCapital'] = Decimal(balanceLockedCapital['sums']) if balanceLockedCapital['sums'] else 0
        # 结余锁仓补贴
        balanceLockedSupport = _recordIncomesLocked.filter((Q(orderStatus='LOCKED') | Q(orderStatus='UNLOCKED')),scene='goldCustom', ).aggregate(sums=Sum('money2'))
        data['balanceLockedSupport'] = Decimal(balanceLockedSupport['sums']) if balanceLockedSupport['sums'] else 0
        # 释放锁仓资产总额
        freeProperayAll = _recordIncomes.filter(Q(orderStatus='FINISH'), scene='unlockedIncomes', ).aggregate(sums=Sum('money'))
        data['freeProperayAll'] = Decimal(freeProperayAll['sums']) if freeProperayAll['sums'] else 0
        year = date.strftime('%Y')
        month = date.strftime('%m')
        day = date.strftime('%d')
        print('dateCycle', dateCycle, year, month, day)
        _itemOrderReturn = None
        if dateCycle == 'day':
            data['dateValue'] = datetime.datetime.strptime(year + '-' + month + '-' + day, "%Y-%m-%d")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN',retunMoneyTime__year=year, retunMoneyTime__month=month, retunMoneyTime__day=day)
            _itemOrder = _itemOrder.filter(payTime__year=year, payTime__month=month, payTime__day=day)
            _recordIncomes = _recordIncomes.filter(createTime__year=year, createTime__month=month, createTime__day=day)
            _recordIncomesLocked = _recordIncomesLocked.filter(createTime__year=year, createTime__month=month, createTime__day=day)
        elif dateCycle == 'month':
            data['dateValue'] = datetime.datetime.strptime(year + '-' + month, "%Y-%m")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN', retunMoneyTime__year=year, retunMoneyTime__month=month)
            _itemOrder = _itemOrder.filter(payTime__year=year, payTime__month=month)
            _recordIncomes = _recordIncomes.filter(createTime__year=year, createTime__month=month)
            _recordIncomesLocked = _recordIncomesLocked.filter(createTime__year=year, createTime__month=month)
        elif dateCycle == 'year':
            data['dateValue'] = datetime.datetime.strptime(year, "%Y")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN', retunMoneyTime__year=year)
            _itemOrder = _itemOrder.filter(payTime__year=year)
            _recordIncomes = _recordIncomes.filter(createTime__year=year)
            _recordIncomesLocked = _recordIncomesLocked.filter(createTime__year=year)
        # print('data', data)
        # 微信支付
        realPayForWxPay = _itemOrder.filter(payway='wxpay').aggregate(sums=Sum('realPay'))
        data['realPayForWxPay'] = Decimal(realPayForWxPay['sums']) if realPayForWxPay['sums'] else 0
        # 微信支付退款
        realPayForWxPayReturn = _itemOrderReturn.filter(payway='wxpay').aggregate(sums=Sum('realPay'))
        data['realPayForWxPayReturn'] = Decimal(realPayForWxPayReturn['sums']) if realPayForWxPayReturn['sums'] else 0
        # 积分支付
        realPayForIncomes = _itemOrder.filter(payway='incomes').aggregate(sums=Sum('realPay'))
        data['realPayForIncomes'] = Decimal(realPayForIncomes['sums']) if realPayForIncomes['sums'] else 0
        # 积分支付退款
        realPayForIncomesReturn = _itemOrderReturn.filter(payway='incomes').aggregate(sums=Sum('realPay'))
        data['realPayForIncomesReturn'] = Decimal(realPayForIncomesReturn['sums']) if realPayForIncomesReturn['sums'] else 0

        # 新增用户提现
        newOutMoney = _recordIncomes.filter((Q(orderStatus='WAIT_SEND')|Q(orderStatus='FINISH')), scene='outMoney', ).aggregate(sums=Sum('money'))
        data['newOutMoney'] = Decimal(newOutMoney['sums']) if newOutMoney['sums'] else 0
        newOutServiceCharge = _recordIncomes.filter((Q(orderStatus='WAIT_SEND')|Q(orderStatus='FINISH')), scene='outMoney', ).aggregate(sums=Sum('serviceCharge'))
        data['newOutServiceCharge'] = Decimal(newOutServiceCharge['sums']) if newOutServiceCharge['sums'] else 0
        # 新增锁仓本金
        newLockedCapital = _recordIncomesLocked.filter((Q(orderStatus='LOCKED') | Q(orderStatus='UNLOCKED')),scene='goldCustom', ).aggregate(sums=Sum('money'))
        data['newLockedCapital'] = Decimal(newLockedCapital['sums']) if newLockedCapital['sums'] else 0
        # 新增锁仓补贴
        newLockedSupport = _recordIncomesLocked.filter((Q(orderStatus='LOCKED') | Q(orderStatus='UNLOCKED')),scene='goldCustom', ).aggregate(sums=Sum('money2'))
        data['newLockedSupport'] = Decimal(newLockedSupport['sums']) if newLockedSupport['sums'] else 0
        # 新增释放锁仓资产
        newFreeProperay = _recordIncomes.filter(Q(orderStatus='FINISH'), scene='unlockedIncomes', ).aggregate(sums=Sum('money'))
        data['newFreeProperay'] = Decimal(newFreeProperay['sums']) if newFreeProperay['sums'] else 0
        print('data', data)
        FinanceForLesseeDao().create(data)

def startFinance():
    financeFun('day', datetime.datetime.now())
    financeFun('month', datetime.datetime.now())
    financeFun('year', datetime.datetime.now())

def startFinanceHistory():
    date_list = []
    begin_date = '2024-05-01'
    begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
    end_date = '2024-05-10'
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")

    while begin_date <= end_date:
        # date_str = begin_date.strftime("%Y-%m-%d")
        date_list.append(begin_date)
        begin_date += datetime.timedelta(days=1)

    print('date_list', date_list)
    for day in date_list:
        financeFun('day', day)
        # financeFun('month', datetime.datetime.now())
        # financeFun('year', datetime.datetime.now())
    for month in range(1):
        month = '2024-' + str(month+5)
        month = datetime.datetime.strptime(str(month), "%Y-%m")
        print('month', month)
        financeFun('month', month)